package com.mvp.shq.washer.ui.shop.order.orderpay;

import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.jaeger.library.StatusBarUtil;
import com.mvp.shq.washer.R;
import com.mvp.shq.washer.adapter.OrderAllPayListAdapter;
import com.mvp.shq.washer.adapter.OrderListAdapter;
import com.mvp.shq.washer.adapter.OrderPayListAdapter;
import com.mvp.shq.washer.base.BaseActivity;
import com.mvp.shq.washer.entity.PayResult;
import com.mvp.shq.washer.entity.WxPayBean;
import com.mvp.shq.washer.entity.result.AlipayResult;
import com.mvp.shq.washer.entity.result.AuthResult;
import com.mvp.shq.washer.entity.result.WxPayResult;
import com.mvp.shq.washer.entity.shop.AddressData;
import com.mvp.shq.washer.entity.shop.Product;
import com.mvp.shq.washer.entity.shop.ProductUnit;
import com.mvp.shq.washer.entity.shop.TotalOrderData;
import com.mvp.shq.washer.entity.shop.TotalOrderListData;
import com.mvp.shq.washer.entity.shop.result.OrderDataListResult;
import com.mvp.shq.washer.entity.shop.result.OrderDataResult;
import com.mvp.shq.washer.entity.shop.result.OrderDetailListRestult;
import com.mvp.shq.washer.entity.shop.result.OrderResult;
import com.mvp.shq.washer.entity.shop.result.ShopAliPayResult;
import com.mvp.shq.washer.rxbus.RxBus;
import com.mvp.shq.washer.rxbus.Subscribe;
import com.mvp.shq.washer.utils.DataDictionary;
import com.mvp.shq.washer.utils.DateUtils;
import com.mvp.shq.washer.utils.EventCode;
import com.mvp.shq.washer.utils.JumpUtil;
import com.mvp.shq.washer.utils.RecyclerViewDivider;
import com.mvp.shq.washer.utils.SpUtil;
import com.mvp.shq.washer.utils.StringUtils;
import com.mvp.shq.washer.utils.T;
import com.mvp.shq.washer.view.widget.CustomDialog;
import com.mvp.shq.washer.view.widget.PayTypePopupWindow;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by westing on 2017/10/11.
 * 待支付界面
 */
public class OrderPayActivity extends BaseActivity<Presenter, Model> implements OrderPayConstract.View {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.order_lasttiem)
    TextView orderLasttiem;//剩余支付时间
    @BindView(R.id.address_person)
    TextView addressPerson;//收件人
    @BindView(R.id.address_phone)
    TextView addressPhone;//收件电话
    @BindView(R.id.tv_address)
    TextView tvAddress;//收件地址
    @BindView(R.id.lin_address)
    LinearLayout linAddress;//收件地址选择
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.order_money1)
    TextView orderMoney1;//商品总价 元
    @BindView(R.id.order_add1)
    TextView orderAdd1;//商品总价加
    @BindView(R.id.order_ji1)
    TextView orderJi1;//商品总价 积分
    @BindView(R.id.order_sendmoney)
    TextView orderSendmoney;//配送费
    @BindView(R.id.tv_money_1)
    TextView tvMoney1;//需支付金额 元
    @BindView(R.id.tv_money2)
    TextView tvMoney2;//需支付金额 角分
    @BindView(R.id.ll_money)
    LinearLayout llMoney;
    @BindView(R.id.tv_add)
    TextView tvAdd;
    @BindView(R.id.tv_integral)
    TextView tvIntegral;//需支付积分
    @BindView(R.id.ll_integral)
    LinearLayout llIntegral;
    @BindView(R.id.orderid)
    TextView orderid;//订单id
    @BindView(R.id.orderpayid)
    TextView orderpayid;//支付id
    @BindView(R.id.order_createtime)
    TextView orderCreatetime;//创建时间
    @BindView(R.id.tv_money_fu1)
    TextView tvMoneyFu1;//支付金额元
    @BindView(R.id.tv_money_fu2)
    TextView tvMoneyFu2;//支付金额角分
    @BindView(R.id.tv_fu_add)
    TextView tvFuAdd;//加号
    @BindView(R.id.tv_fu_ji)
    TextView tvFuJi;//积分
    @BindView(R.id.bnt_pay)
    Button bntPay;
    @BindView(R.id.tv_jifen)
    TextView tvJifen;//积分文字
    @BindView(R.id.tv_jifen2)
    TextView tvJifen2;//积分文字
    @BindView(R.id.lin_money2)
    LinearLayout lin_money2;
    private int currerPosition;
    private PayTypePopupWindow popupWindow;
    private final static int PAYWALLET = 0;//钱包支付
    private final static int PAYWX = 1;//微信支付
    private final static int PAYALI = 2;//支付宝
    private IWXAPI api;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private int payType;
    private String payModel;
    private CustomDialog integoryDialog;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        //Toast.makeText(PayDemoActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                        paySuccess();

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        //Toast.makeText(PayDemoActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                        T.show("支付失败");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
//                                .show();
                        T.show("授权成功");
                    } else {
                        // 其他状态值则为授权失败
//                        Toast.makeText(PayDemoActivity.this,
//                                "授权失败" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT).show();
                        T.show("授权失败");

                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    private String orderId;
    private String orderNo;
    private OrderDataListResult orderDetail;

    private int FROM_TYPE = 0;//跳转来源 0 订单列表  1 提交订单

    @Override
    public int getLayoutId() {
        return R.layout.activity_orderpay;
    }

    @Override
    public void initView() {
        StatusBarUtil.setColor(this, ContextCompat.getColor(context, R.color.money), 9);
        title.setText("订单付款");
        recyclerview.setLayoutManager(new LinearLayoutManager(context));
        RecyclerViewDivider divider = new RecyclerViewDivider(context, LinearLayoutManager.HORIZONTAL, 10, ContextCompat.getColor(context, R.color.white));
        recyclerview.addItemDecoration(divider);
        FROM_TYPE = getIntent().getIntExtra("type",0);
        orderId = getIntent().getStringExtra("orderId");
        if (FROM_TYPE == 0){
            showLoadingDialog(true);
            presenter.getOrderInfo(orderId);
        }else if (FROM_TYPE == 1){
            RxBus.get().send(EventCode.SHOP_ORDER_GET_ORDER);
        }

    }

    @Subscribe(code = EventCode.SHOP_ORDER_SEND_ORDER)
    public void getOrderInfo(OrderDataResult orderResult) {
        if (orderResult != null) {
            orderId = orderResult.getId();
            orderNo = orderResult.getOrderNo();
            List<OrderDataListResult> orderList = orderResult.getEcOrderList();
            //显示金额
            updateMoney(orderList);
            //订单剩余时间
            updateLastTime(orderResult.getCreateDate());
            //地址
            updateAddress(orderResult.getEcOrderList().get(0).getConsigneeName(),orderResult.getEcOrderList().get(0).getConsigneeMobile(),
                    orderResult.getEcOrderList().get(0).getAddressDes());

            //订单信息
            updateOrderInfo(orderResult.getId(),orderResult.getOrderNo(),orderResult.getEcOrderList().get(0).getCreateDate());
        }
    }

    /**
     * 显示金额
     * @param orderList
     */
    private void updateMoney(List<OrderDataListResult> orderList){
        double cashPrice = 0, integralPrice = 0;
        for (int i = 0, len = orderList.size(); i < len; i++) {
            List<OrderDetailListRestult> o = orderList.get(i).getEcOrderDetailList();
            for (int j = 0, lenj = o.size(); j < lenj; j++) {
                OrderDetailListRestult or = o.get(j);
                cashPrice += or.getCashPrice() * or.getNum();
                integralPrice += or.getIntegralPrice() * or.getNum();
            }
        }
        //商品总价
        if (cashPrice == 0) {
            payModel = DataDictionary.PAY_MODE_INTEGRAL;
            orderMoney1.setVisibility(View.GONE);
            orderAdd1.setVisibility(View.GONE);

            llMoney.setVisibility(View.GONE);
            tvAdd.setVisibility(View.GONE);

            lin_money2.setVisibility(View.GONE);
            tvFuAdd.setVisibility(View.GONE);

        } else if (integralPrice == 0) {
            payModel = DataDictionary.PAY_MODE_CASH;
            orderJi1.setVisibility(View.GONE);
            orderAdd1.setVisibility(View.GONE);
            tvAdd.setVisibility(View.GONE);
            tvIntegral.setVisibility(View.GONE);
            tvFuJi.setVisibility(View.GONE);
            tvFuAdd.setVisibility(View.GONE);
            tvJifen.setVisibility(View.GONE);
            tvJifen2.setVisibility(View.GONE);
        }else {
            payModel = DataDictionary.PAY_MODE_CASH_AND_INTEGRAL;
        }
        orderMoney1.setText("￥" + cashPrice);
        orderJi1.setText((int) integralPrice + "积分");
        //需付款
        tvMoney1.setText((int) cashPrice + "");
        tvMoney2.setText(StringUtils.BigDecimalToStr(BigDecimal.valueOf(cashPrice)));
        tvIntegral.setText((int) integralPrice + "");
        tvMoneyFu1.setText((int) cashPrice + "");
        tvMoneyFu2.setText(StringUtils.BigDecimalToStr(BigDecimal.valueOf(cashPrice)));
        tvFuJi.setText((int) integralPrice + "");
        OrderAllPayListAdapter listadapter = new OrderAllPayListAdapter(context, orderList);
        recyclerview.setAdapter(listadapter);
    }

    /**
     * 显示当前订单剩余时间
     * @param creatTime
     */
    private void updateLastTime(String creatTime){
        String time = DateUtils.compareTimeToFormat(creatTime);
        if (TextUtils.isEmpty(time)) {
            //已超过15分钟，关闭订单
            orderLasttiem.setText("订单超过15分钟，已自动关闭");
        } else {
            orderLasttiem.setText("剩" + time + "自动关闭订单");
        }
    }

    /**
     * 显示地址信息
     * @param consigneeName
     * @param consigneeMobile
     * @param addressDes
     */
    private void updateAddress(String consigneeName,String consigneeMobile,String addressDes){
        //收件人
        addressPerson.setText("" + consigneeName);
        //收件电话
        addressPhone.setText("" + consigneeMobile);
        //收件地址
        tvAddress.setText(addressDes);
    }

    /**
     * 显示订单信息
     * @param orderId
     * @param orderNo
     * @param createDate
     */
    private void updateOrderInfo(String orderId,String orderNo,String createDate){
        //订单id
        orderid.setText("订单编号：" + orderId);
        //支付id
        orderpayid.setText("交易号：" + orderNo);
        //创建时间
        orderCreatetime.setText("创建时间:" + createDate);
    }

    @OnClick({R.id.back, R.id.bnt_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.bnt_pay:
//                JumpUtil.toOrderTake(context);
                showPopPayType();
                break;

        }
    }

    /**
     * 显示支付选择对话框
     */
    private void showPopPayType() {
        if (payModel.equals(DataDictionary.PAY_MODE_INTEGRAL)){
            CustomDialog.Builder builder = new CustomDialog.Builder(context);
            if (integoryDialog == null){
                integoryDialog = builder.setMessage("使用积分直接支付")
                        .setNegativeButton("确认", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                integoryDialog.dismiss();
                                showLoadingDialog(true);
                                presenter.wxPay(orderNo);
                            }
                        })
                        .setPositiveButton("取消", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        }).createTwoButtonDialog();
            }
            integoryDialog.show();
            return;
        }
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.7f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
        if (popupWindow == null) {
            popupWindow = new PayTypePopupWindow(context, this, new PayTypePopupWindow.OnCheckListener() {
                @Override
                public void onCheck(int position) {
                    currerPosition = position;
                }
            }, "13.00", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (currerPosition) {
                        case PAYWALLET:
                            //钱包支付
                            //JumpUtil.toOrderTake(context, mOrderResult.getOrderNo());
                            break;
                        case PAYWX:
                            //微信支付
                            showLoadingDialog(true);
                            if (FROM_TYPE == 0){
                                payType = PAYWX;
                                presenter.createOrder(orderDetail);
                            }else {
                                presenter.wxPay(orderNo);
                            }
                            popupWindow.dismiss();
                            break;
                        case PAYALI:
                            //支付宝
                            showLoadingDialog(true);
                            if (FROM_TYPE == 0){
                                payType = PAYALI;
                                presenter.createOrder(orderDetail);
                            }else {
                                presenter.alipay(orderNo);
                            }
                            popupWindow.dismiss();
                            break;
                    }
                }
            });
        }
        popupWindow.showAtLocation(back, Gravity.BOTTOM, 0, 0);
    }

    private void alipay(String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(OrderPayActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void alipayS(ShopAliPayResult result) {
        if (result != null && result.getAlipay().isSuccess()) {
            alipay(result.getAlipay().getBody());
        }else {
            paySuccess();
        }
    }

    @Override
    public void wxPayS(WxPayResult result) {
        if (result != null && result.getWxpay() != null) {
            WxPayBean payBean = result.getWxpay();
            api = WXAPIFactory.createWXAPI(context, null);
            api.registerApp(payBean.getAppid());
            PayReq request = new PayReq();
            request.appId = payBean.getAppid();
            request.partnerId = payBean.getPartnerid();
            request.prepayId = payBean.getPrepayid();
            request.packageValue = payBean.getPackageX();
            request.nonceStr = payBean.getNoncestr();
            request.timeStamp = payBean.getTimestamp();
            request.sign = payBean.getSign();
            api.sendReq(request);
        }else {
            paySuccess();
        }
    }

    @Override
    public void createOrder(OrderDataResult orderResult) {
        if (orderResult == null){
            T.show("请求错误");
            return;
        }
        orderId = orderResult.getId();
        orderNo = orderResult.getOrderNo();
        if (payType == PAYALI){
            //支付宝
            presenter.alipay(orderNo);
        }else if (payType == PAYWX){
            //微信
            presenter.wxPay(orderNo);
        }
    }

    @Override
    public void getOrderInfoS(OrderDataListResult result) {
        orderDetail = result;
        List<OrderDataListResult> orderList = new ArrayList<>();
        orderList.add(result);
        updateMoney(orderList);
        updateLastTime(result.getCreateDate());
        updateAddress(result.getConsigneeName(),result.getConsigneeMobile(),result.getAddressDes());
        updateOrderInfo(result.getId(),result.getOrderNo(),result.getCreateDate());
    }

    @Subscribe(code = EventCode.SHOP_PAY_SUCCESS)
    public void paySuccess(){
        T.show("支付成功");
        //待收货
        //JumpUtil.toOrderTake(context, orderId);
        finish();
    }
}
